package com.dzl.cloud.controller;

import com.dzl.cloud.dto.LogMessageDTO;
import com.dzl.cloud.produce.PermissionLogService;
import com.dzl.cloud.service.UserRoleService;
import com.dzl.cloud.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dzl.cloud.util.JwtUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 光的代言人
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private PermissionLogService permissionLogService;

    // 绑定默认角色（普通用户）
    @PostMapping("/bind-default-role")
    public Result bindDefaultRole(@RequestParam("userId") Long userId) {
        userRoleService.bindDefaultRole(userId);
        return Result.success();
    }

    // 查询用户角色编码
    @GetMapping("/get-user-role-code")
    public String getUserRoleCode(@RequestParam("userId") Long userId) {
        return userRoleService.getUserRoleCode(userId);
    }

    // 升级用户为管理员
//    @PreAuthorize("hasRole('super_admin')")
    @PostMapping("/upgrade-to-admin")
    public Result upgradeToAdmin(@RequestParam("userId") Long userId, @RequestHeader("Authorization") String token, HttpServletRequest request) {
        Long userIdDone = JwtUtils.getUserIdFromToken(token);
        userRoleService.upgradeToAdmin(userId, userIdDone);
        // 发送MQ 日志
        LogMessageDTO message = new LogMessageDTO();
        message.setUserId(userIdDone);
        message.setAction("USER_UPGRADE_TO_ADMIN");
        message.setIp(getClientIp(request));
        message.setDetail("用户【"+userId+"】 升级为管理员成功!");
        permissionLogService.sendLog(message);
        return Result.success("用户已升级为管理员！");
    }

    // 获取客户端IP（AI生成）
    private String getClientIp(HttpServletRequest request) {
        // 获取X-Forwarded-For头信息，如果有多个IP，取第一个
        String ip = request.getHeader("X-Forwarded-For");

        // 如果是通过负载均衡或代理服务器访问，X-Forwarded-For可能有多个IP
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 获取代理服务器传来的IP
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 获取通过HTTP请求的客户端IP
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            // 获取请求来源IP
            ip = request.getRemoteAddr();
        }
        // 如果有多个IP，X-Forwarded-For会以逗号分隔，返回第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        // 如果获取到的 IP 是回环地址（0:0:0:0:0:0:0:1），处理为 127.0.0.1 或者其他默认值
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            // 你可以选择返回 "localhost" 或其他默认值
            ip = "127.0.0.1";
        }

        return ip;
    }

    // 降级用户为普通角色
    @PostMapping("/downgrade-to-user")
    public Result downgradeToUser(@RequestParam("userId") Long userId, @RequestHeader("Authorization") String token, HttpServletRequest request) {
        // 解析token,获取当前用户ID
        Long userIdDone=JwtUtils.getUserIdFromToken(token);
        userRoleService.downgradeToUser(userId, userIdDone);
        // 发送日志
        LogMessageDTO message = new LogMessageDTO();
        message.setUserId(userIdDone);
        message.setAction("ADMIN_DOWNGRADE_TO_USER");
        message.setIp(getClientIp(request));
        message.setDetail("用户【"+userId+"】 已降级为普通用户!");
        permissionLogService.sendLog(message);
        return Result.success("用户已降级为普通用户！");
    }

    /**
     * 根据角色码查询用户ID列表
     *
     * @param roleCode 角色码（如"user"）
     * @return 用户ID列表
     */
    @GetMapping("/select-userIds-by-Role/{roleCode}")
    public List<Long> getUserIdsByRole(@PathVariable("roleCode") String roleCode) {
        return userRoleService.getUserIdsByRole(roleCode);
    }
}